import pandas as pd
from utils import log_info, log_exception, log_debug
from services.importers.base_importer import BaseImporter


class CSVImporter(BaseImporter):
    """CSV文件导入器"""

    def read_file(self, file_path, progress_var=None, progress_label=None, import_dialog=None):
        """读取CSV文件并解析为题目数据"""
        try:
            log_debug(f"开始处理CSV文件: {file_path}")
            # 读取CSV文件，不将第一行作为标题行
            df = pd.read_csv(file_path, header=None)
            questions = df.to_dict('records')
            total = len(questions)
            log_debug(f"成功读取CSV文件，共{total}道题目")

            # 转换索引为字段名
            formatted_questions = []
            for q in questions:
                # 检查必要字段 (索引3: Q, 5:A, 6:B, 7:C, 8:D, 4:T, 9:F, 13:type)
                required_indices = [3, 5, 6, 7, 8, 4, 9, 13]
                if not all(idx in q for idx in required_indices):
                    continue

                # 处理空值
                for key in q:
                    if pd.isna(q[key]):
                        q[key] = ''

                # 转换为字典格式，使用字段名而非索引
                formatted_q = {
                    'J': q.get(0, ''),
                    'P': q.get(1, ''),
                    'I': q.get(2, ''),
                    'Q': q.get(3, ''),
                    'T': q.get(4, ''),
                    'A': q.get(5, ''),
                    'B': q.get(6, ''),
                    'C': q.get(7, ''),
                    'D': q.get(8, ''),
                    'F': q.get(9, ''),
                    'LA': int(float(q.get(10, 0) or 0)),
                    'LB': int(float(q.get(11, 0) or 0)),
                    'LC': int(float(q.get(12, 0) or 0)),
                    'type': int(q.get(13, 0))
                }
                formatted_questions.append(formatted_q)

            return formatted_questions
        except Exception as e:
            log_exception(f"处理CSV数据时发生异常: {str(e)}")
            return []

def process_csv_data(file_path, progress_var=None, progress_label=None, import_dialog=None):
    """处理CSV数据并导入数据库"""
    importer = CSVImporter()
    return importer.process_data(file_path, progress_var, progress_label, import_dialog)
    